// js/utils/LoadingManager.js
export default class LoadingManager {
  constructor(canvas, ctx, screenAdapter, type = 'global') {
    this.canvas = canvas;
    this.ctx = ctx;
    this.screenAdapter = screenAdapter;
    this.type = type; // 'global' 或 'page'

    // 加载动画相关属性
    this.progress = 0;
    this.targetProgress = 0;
    this.rotation = 0;
    this.particles = [];
    this.isActive = false;

    // 淡入淡出相关属性
    this.opacity = 0;
    this.targetOpacity = 0;
    this.isFadingOut = false;
    this.fadeOutCallback = null;

    // 加载logo图片
    this.logoImage = null;
    this.loadLogoImage();

    this.onInit();
  }

  async loadLogoImage() {
    return new Promise((resolve) => {
      const image = wx.createImage();
      image.onload = () => {
        this.logoImage = image;
        resolve();
      };
      image.onerror = () => {
        console.warn('Failed to load logo image');
        resolve();
      };
      image.src = 'https://www.zmkxds.cn/images/loadingLog.png';
    });
  }

  onInit() {
    // 根据类型创建不同数量的背景粒子
    const particleCount = this.type === 'global' ? 20 : 10;
    for (let i = 0; i < particleCount; i++) {
      this.particles.push({
        x: Math.random() * this.screenAdapter.DESIGN_WIDTH,
        y: Math.random() * this.screenAdapter.DESIGN_HEIGHT,
        size: Math.random() * 3 + 1,
        speedX: (Math.random() - 0.5) * 0.5,
        speedY: (Math.random() - 0.5) * 0.5,
        opacity: Math.random() * 0.5 + 0.2
      });
    }
  }

  start() {
    this.isActive = true;
    this.isFadingOut = false;
    this.progress = 0;
    this.targetProgress = 0;
    this.targetOpacity = 1; // 开始时淡入到完全不透明
  }

  stop() {
    // 不要立即停止，而是开始淡出
    this.isFadingOut = true;
    this.targetOpacity = 0;
  }

  // 设置淡出完成后的回调
  setFadeOutCallback(callback) {
    this.fadeOutCallback = callback;
  }

  setProgress(progress) {
    this.targetProgress = Math.min(100, Math.max(0, progress));
  }

  update(deltaTime) {
    if (!this.isActive) return;

    // 平滑进度更新
    if (this.progress < this.targetProgress) {
      this.progress = Math.min(this.targetProgress, this.progress + deltaTime * 0.1);
    }

    // 旋转动画
    this.rotation += deltaTime * 0.002;

    // 透明度更新（淡入淡出）
    if (this.opacity < this.targetOpacity) {
      this.opacity = Math.min(this.targetOpacity, this.opacity + deltaTime * 0.003);
    } else if (this.opacity > this.targetOpacity) {
      this.opacity = Math.max(this.targetOpacity, this.opacity - deltaTime * 0.003);
    }

    // 如果正在淡出且透明度为0，则完全停止
    if (this.isFadingOut && this.opacity <= 0) {
      this.isActive = false;
      if (this.fadeOutCallback) {
        this.fadeOutCallback();
        this.fadeOutCallback = null;
      }
    }

    // 更新粒子
    this.particles.forEach(particle => {
      particle.x += particle.speedX;
      particle.y += particle.speedY;

      // 边界检测
      if (particle.x < 0 || particle.x > this.screenAdapter.DESIGN_WIDTH) {
        particle.speedX *= -1;
      }
      if (particle.y < 0 || particle.y > this.screenAdapter.DESIGN_HEIGHT) {
        particle.speedY *= -1;
      }
    });
  }

  render() {
    if (!this.isActive || !this.ctx) return;

    const ctx = this.ctx;
    const { DESIGN_WIDTH, DESIGN_HEIGHT } = this.screenAdapter;

    // 检查 context 是否有效
    if (!ctx || typeof ctx.fillRect !== 'function') {
      console.warn('Canvas context is not valid');
      return;
    }

    // 保存当前全局透明度
    ctx.save();
    ctx.globalAlpha = this.opacity;

    // 深色渐变背景 - 添加错误处理
    try {
      const gradient = ctx.createLinearGradient(0, 0, 0, DESIGN_HEIGHT);
      gradient.addColorStop(0, '#0f0c29');
      gradient.addColorStop(0.5, '#302b63');
      gradient.addColorStop(1, '#24243e');
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, DESIGN_WIDTH, DESIGN_HEIGHT);
    } catch (error) {
      // 如果 gradient 创建失败，使用纯色背景
      console.warn('Failed to create gradient, using solid color:', error);
      ctx.fillStyle = '#1a1a2e';
      ctx.fillRect(0, 0, DESIGN_WIDTH, DESIGN_HEIGHT);
    }

    // 绘制背景粒子
    this.particles.forEach(particle => {
      ctx.save();
      ctx.globalAlpha = particle.opacity * this.opacity;
      ctx.fillStyle = '#ffffff';
      ctx.beginPath();
      ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
      ctx.fill();
      ctx.restore();
    });

    // 根据类型渲染不同内容
    if (this.type === 'global') {
      this.renderGlobalLoading();
    } else {
      this.renderPageLoading();
    }

    // 恢复全局透明度
    ctx.restore();
  }

  renderGlobalLoading() {
    const ctx = this.ctx;
    const { DESIGN_WIDTH, DESIGN_HEIGHT } = this.screenAdapter;
    const centerX = DESIGN_WIDTH / 2;
    const centerY = DESIGN_HEIGHT / 2;

    // 绘制logo图片或文字
    this.renderLogo(centerX, centerY - 140);

    // 旋转的加载图标
    this.drawLoadingIcon(centerX, centerY + 20);

    // 进度条
    const progressBarWidth = 300;
    const progressBarHeight = 8;
    const progressBarX = (DESIGN_WIDTH - progressBarWidth) / 2;
    const progressBarY = centerY + 80;

    // 进度条背景
    ctx.fillStyle = 'rgba(255, 255, 255, 0.1)';
    ctx.fillRect(progressBarX, progressBarY, progressBarWidth, progressBarHeight);

    // 进度条
    const progressWidth = (progressBarWidth * this.progress) / 100;

    // 进度条渐变 - 添加错误处理
    try {
      const progressGradient = ctx.createLinearGradient(progressBarX, 0, progressBarX + progressWidth, 0);
      progressGradient.addColorStop(0, '#667eea');
      progressGradient.addColorStop(1, '#764ba2');
      ctx.fillStyle = progressGradient;
    } catch (error) {
      // 如果 gradient 创建失败，使用纯色
      ctx.fillStyle = '#667eea';
    }

    ctx.fillRect(progressBarX, progressBarY, progressWidth, progressBarHeight);

    // 进度百分比
    ctx.save();
    ctx.fillStyle = '#ffffff';
    ctx.font = '24px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(`${Math.floor(this.progress)}%`, centerX, progressBarY + 40);
    ctx.restore();

    // 加载提示文字
    const loadingTexts = [
      '正在连接行情服务器...',
      '加载K线数据中...',
      '准备就绪...'
    ];
    const textIndex = Math.floor(this.progress / 34);
    const loadingText = loadingTexts[Math.min(textIndex, loadingTexts.length - 1)];

    ctx.save();
    ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
    ctx.font = '18px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(loadingText, centerX, progressBarY + 80);
    ctx.restore();
  }

  renderPageLoading() {
    const ctx = this.ctx;
    const { DESIGN_WIDTH, DESIGN_HEIGHT } = this.screenAdapter;
    const centerX = DESIGN_WIDTH / 2;
    const centerY = DESIGN_HEIGHT / 2;

    // 简单的页面切换提示
    ctx.save();
    ctx.fillStyle = '#ffffff';
    ctx.font = '24px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('加载中...', centerX, centerY);
    ctx.restore();

    // 小型旋转图标
    this.drawLoadingIcon(centerX, centerY + 40, 20);
  }

  renderLogo(centerX, centerY) {
    if (this.logoImage) {
      // 绘制logo图片
      const logoWidth = 450;
      const logoHeight = 164;
      this.ctx.drawImage(
        this.logoImage,
        centerX - logoWidth / 2,
        centerY - logoHeight / 2,
        logoWidth,
        logoHeight
      );
    } else {
      // 如果图片还没加载完成，显示文字
      this.ctx.save();
      this.ctx.fillStyle = '#ffffff';
      this.ctx.font = 'bold 48px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
      this.ctx.textAlign = 'center';
      this.ctx.textBaseline = 'middle';
      this.ctx.shadowColor = 'rgba(255, 255, 255, 0.5)';
      this.ctx.shadowBlur = 20;
      this.ctx.fillText('哲鸣K线大师', centerX, centerY);
      this.ctx.restore();
    }
  }

  drawLoadingIcon(x, y, radius = 30) {
    const ctx = this.ctx;

    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(this.rotation);

    // 外圈
    ctx.strokeStyle = 'rgba(102, 126, 234, 0.3)';
    ctx.lineWidth = 4;
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, Math.PI * 2);
    ctx.stroke();

    // 内圈（旋转部分）
    try {
      const gradient = ctx.createLinearGradient(-radius, -radius, radius, radius);
      gradient.addColorStop(0, '#667eea');
      gradient.addColorStop(1, '#764ba2');
      ctx.strokeStyle = gradient;
    } catch (error) {
      // 如果 gradient 创建失败，使用纯色
      ctx.strokeStyle = '#667eea';
    }

    ctx.lineWidth = 4;
    ctx.lineCap = 'round';
    ctx.beginPath();
    ctx.arc(0, 0, radius, -Math.PI / 2, Math.PI / 2);
    ctx.stroke();

    // 中心点
    ctx.fillStyle = '#ffffff';
    ctx.beginPath();
    ctx.arc(0, 0, 4, 0, Math.PI * 2);
    ctx.fill();

    ctx.restore();
  }
}
